package cn.edu.whu.forecast.controller;

import cn.edu.whu.forecast.cache.CacheEntity;
import cn.edu.whu.forecast.cache.CacheManagerImpl;
import cn.edu.whu.forecast.common.ResultBean;
import cn.edu.whu.forecast.entity.mysql.AvgRainfallAllForecast;
import cn.edu.whu.forecast.entity.mysql.RadarRecord;
import cn.edu.whu.forecast.entity.mysql.SectionFlowWaterLevel;
import cn.edu.whu.forecast.service.impl.RadarServiceImpl;
import cn.edu.whu.forecast.service.impl.RainfallServiceImpl;
import cn.edu.whu.forecast.service.impl.SectionServiceImpl;
import cn.edu.whu.forecast.service.impl.WarningRecordServiceImpl;
import cn.edu.whu.forecast.util.CSVFileUtil;
import cn.edu.whu.forecast.util.ExcelFileUtil;
import cn.edu.whu.forecast.util.HttpClientUtil;
import cn.edu.whu.forecast.util.JsonFileUtil;
import cn.edu.whu.forecast.vo.request.AddWarningRecordVo;
import cn.edu.whu.forecast.vo.response.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {
    @Resource
    private RainfallServiceImpl rainfallService;

    @Resource
    private SectionServiceImpl sectionService;

    @Resource
    private WarningRecordServiceImpl warningRecordService;

    @Resource
    private CacheManagerImpl cacheManager;

    @Resource
    private RadarServiceImpl radarService;

    @GetMapping("/createCSV1")
    private ResultBean<?> createCSV1(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("date") Date date) {
        List<List<Object>> heads = new ArrayList<>();
        Object[] head1 = new Object[]{"LGTD", 118.1, 118.216666, 118.17017, 118.15127, 118.216666, 118.266666, 118.2975};
        Object[] head2 = new Object[]{"LTTD", 25.433333, 25.433333, 25.3825, 25.31467, 25.35, 25.4, 25.3167};
        Object[] head3 = new Object[]{"STNM", "锦溪", "嵩山", "蓬壶", "达中", "大卿", "天马", "永春"};
        heads.add(Arrays.asList(head1));
        heads.add(Arrays.asList(head2));
        heads.add(Arrays.asList(head3));
        List<List<Object>> dataList = new ArrayList<>();
        List<Object> tmp = new ArrayList<>();
        List<RainfallVo> rainfallByTime = rainfallService.getRainfallByTime(date);
        tmp.add(new SimpleDateFormat("yyyyMMddHHmm").format(rainfallByTime.get(0).getTime()));
        for (RainfallVo rainfallVo : rainfallByTime) {
            tmp.add(rainfallVo.getRainfall());
        }
        dataList.add(tmp);

        String fileName = "testCSV.csv";
        String filePath = "C:\\Users\\Administrator\\Desktop\\";

        CSVFileUtil.createCSV(heads, dataList, fileName, filePath, true);

        return ResultBean.ok();
    }

    @GetMapping("/createCSV2")
    private ResultBean<?> createCSV2() throws ParseException {

        List<List<Object>> heads = new ArrayList<>();
        Object[] head1 = new Object[]{"LGTD", 118.1, 118.216666, 118.17017, 118.15127, 118.216666, 118.266666, 118.2975};
        Object[] head2 = new Object[]{"LTTD", 25.433333, 25.433333, 25.3825, 25.31467, 25.35, 25.4, 25.3167};
        Object[] head3 = new Object[]{"STNM", "锦溪", "嵩山", "蓬壶", "达中", "大卿", "天马", "永春"};
        heads.add(Arrays.asList(head1));
        heads.add(Arrays.asList(head2));
        heads.add(Arrays.asList(head3));
        List<List<Object>> dataList = new ArrayList<>();


        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = df1.parse("2022-01-01 00:00:00");//格式化日期
        long starTime = date.getTime();//转换时间戳
        long endTime = df1.parse("2022-07-01 00:00:00").getTime();
        long oneHour = 1000 * 60 * 60L;//一个小时

        while (starTime <= endTime) {
            Date d = new Date(starTime);

            List<Object> tmp = new ArrayList<>();

            List<RainfallVo> rainfallByTime = rainfallService.getRainfallByTime(d);
            if (rainfallByTime.size() == 0) {
                starTime += oneHour;
                continue;
            }
            tmp.add(new SimpleDateFormat("yyyyMMddHHmm").format(rainfallByTime.get(0).getTime()));
            for (RainfallVo rainfallVo : rainfallByTime) {
                tmp.add(rainfallVo.getRainfall().doubleValue());
            }
            if (rainfallByTime.size() != 5) {
                for (int i = rainfallByTime.size(); i < 7; i++) {
                    tmp.add((double) 0);
                }
            }

            dataList.add(tmp);

            starTime += oneHour;

        }


        String fileName = "testCSV.csv";
        String filePath = "C:\\Users\\Administrator\\Desktop\\";

        CSVFileUtil.createCSV(heads, dataList, fileName, filePath, true);

        return ResultBean.ok();
    }

    @GetMapping("/createXlsx")
    private ResultBean<?> createCSV3(
            @RequestParam("startTime") String start,
            @RequestParam("endTime") String end
    ) throws Exception {

        FileInputStream fs = new FileInputStream("/home/shanhong/app/python/quanzhou/testXlsx.xlsx");  //获取head.xls
        //POIFSFileSystem ps=new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息
        XSSFWorkbook wb = new XSSFWorkbook(fs);
        XSSFSheet sheet = wb.getSheetAt(0);  //获取到工作表，因为一个excel可能有多个工作表
        XSSFRow row = sheet.getRow(0);  //获取第一行（excel中的行默认从0开始，所以这就是为什么，一个excel必须有字段列头），即，字段列头，便于赋值
        System.out.println(sheet.getLastRowNum() + " " + row.getLastCellNum());  //分别得到最后一行的行号，和一条记录的最后一个单元格

        FileOutputStream out = new FileOutputStream("/home/shanhong/app/python/quanzhou/testXlsx.xlsx");  //向head.xls中写数据

        List<List<Object>> dataList = new ArrayList<>();
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = df1.parse(start);//格式化日期
        long starTime = date.getTime();//转换时间戳
        long endTime = df1.parse(end).getTime();
        long oneHour = 1000 * 60 * 60L;//一个小时

        while (starTime <= endTime) {
            Date d = new Date(starTime);

            List<Object> tmp = new ArrayList<>();

            List<RainfallVo> rainfallByTime = rainfallService.getRainfallByTime(d);
            if (rainfallByTime.size() == 0) {
                starTime += oneHour;
                continue;
            }
            tmp.add(new SimpleDateFormat("yyyyMMddHHmm").format(rainfallByTime.get(0).getTime()));
            for (RainfallVo rainfallVo : rainfallByTime) {
                tmp.add(rainfallVo.getRainfall().doubleValue());
            }
            if (rainfallByTime.size() != 7) {
                for (int i = rainfallByTime.size(); i < 7; i++) {
                    tmp.add((double) 0);
                }
            }

            dataList.add(tmp);

            starTime += oneHour;

        }


        for (List<Object> objects : dataList) {
            row = sheet.createRow((short) (sheet.getLastRowNum() + 1)); //在现有行号后追加数据

            row.createCell(0).setCellValue((objects.get(0).toString()));
            row.createCell(1).setCellValue((double) objects.get(1));
            row.createCell(2).setCellValue((double) objects.get(2));
            row.createCell(3).setCellValue((double) objects.get(3));
            row.createCell(4).setCellValue((double) objects.get(4));
            row.createCell(5).setCellValue((double) objects.get(5));
            row.createCell(6).setCellValue((double) objects.get(6));
            row.createCell(7).setCellValue((double) objects.get(7));

//            row.createCell(0).setCellValue("hello"); //设置第一个（从0开始）单元格的数据
//            row.createCell(1).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(2).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(3).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(4).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(5).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(6).setCellValue(1); //设置第二个（从0开始）单元格的数据
//            row.createCell(7).setCellValue(1); //设置第二个（从0开始）单元格的数据
        }


        out.flush();
        wb.write(out);
        out.close();
        System.out.println(row.getPhysicalNumberOfCells() + " " + row.getLastCellNum());

        return ResultBean.ok();
    }

    @GetMapping("/addXlsx")
    private void addXlsx(
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
            @RequestParam("time") LocalDateTime time
    ) throws IOException {
        Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
        List<Object> tmp = new ArrayList<>();
        List<RainfallVo> rainfallByTime = rainfallService.getRainfallByTime(date);

        if (rainfallByTime.size() == 0) {
            System.out.println("该小时没有数据");
        } else {
            FileInputStream fs = new FileInputStream("/home/shanhong/app/python/quanzhou/testXlsx.xlsx");  //获取head.xls
            XSSFWorkbook wb = new XSSFWorkbook(fs);
            XSSFSheet sheet = wb.getSheetAt(0);  //获取到工作表，因为一个excel可能有多个工作表
            XSSFRow row = sheet.getRow(0);  //获取第一行（excel中的行默认从0开始，所以这就是为什么，一个excel必须有字段列头），即，字段列头，便于赋值
            System.out.println(sheet.getLastRowNum() + " " + row.getLastCellNum());  //分别得到最后一行的行号，和一条记录的最后一个单元格
            FileOutputStream out = new FileOutputStream("/home/shanhong/app/python/quanzhou/testXlsx.xlsx");  //向head.xls中写数据


            tmp.add(new SimpleDateFormat("yyyyMMddHHmm").format(rainfallByTime.get(0).getTime()));
            for (RainfallVo rainfallVo : rainfallByTime) {
                tmp.add(rainfallVo.getRainfall().doubleValue());
            }
            if (rainfallByTime.size() != 7) {
                for (int i = rainfallByTime.size(); i < 7; i++) {
                    tmp.add((double) 0);
                }
            }

            row = sheet.createRow((short) (sheet.getLastRowNum() + 1)); //在现有行号后追加数据

            row.createCell(0).setCellValue((tmp.get(0).toString()));
            row.createCell(1).setCellValue((double) tmp.get(1));
            row.createCell(2).setCellValue((double) tmp.get(2));
            row.createCell(3).setCellValue((double) tmp.get(3));
            row.createCell(4).setCellValue((double) tmp.get(4));
            row.createCell(5).setCellValue((double) tmp.get(5));
            row.createCell(6).setCellValue((double) tmp.get(6));
            row.createCell(7).setCellValue((double) tmp.get(7));


            out.flush();
            wb.write(out);
            out.close();
            System.out.println(row.getPhysicalNumberOfCells() + " " + row.getLastCellNum());
        }
    }


//    @GetMapping("/xajProject")
//    private ResultBean<?> xajProject() {
//
//
//        String s = HttpClientUtil.doGet("http://124.220.210.6:8082/xajPredict");
//        JSONObject object = JSONObject.parseObject(s);
//
//        JSONArray data_flow = object.getJSONArray("dmFlowRate");
//        JSONArray data_waterLevel = object.getJSONArray("dmWaterLevel");
//        JSONArray date_criticalLevel = object.getJSONArray("criticalLevel");
//        List<Integer> list = new ArrayList<>();
//        list.add(2);
//        list.add(12);
//        list.add(13);
//        list.add(55);
//        list.add(58);
//        list.add(69);
//        list.add(91);
//        list.add(92);
//        list.add(119);
//
//        for (int i = 0; i < data_flow.size(); i++) {
//            JSONArray data_flow_one = data_flow.getJSONArray(i);
//            JSONArray data_waterLevel_one = data_waterLevel.getJSONArray(i);
//            for (int j = 0; j < data_flow_one.size() - 1; j++) {
//                SectionFlowWaterLevel sectionFlowWaterLevel = new SectionFlowWaterLevel();
//                sectionFlowWaterLevel.setSectionId(list.get(j));
//                sectionFlowWaterLevel.setFlow(data_flow_one.getBigDecimal(j + 1));
//                sectionFlowWaterLevel.setWaterLevel(data_waterLevel_one.getBigDecimal(j + 1));
//                sectionFlowWaterLevel.setCreatTime(LocalDateTime.parse(data_flow_one.getString(0).replaceAll("T", " "), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//
//                sectionService.addFlowWaterLevel(sectionFlowWaterLevel);
//            }
//        }
//
//        if (date_criticalLevel.getString(1).equals("预警")) {
//            warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 1));
//        } else {
//            warningRecordService.addWarningRecord(new AddWarningRecordVo(date_criticalLevel.getBigDecimal(0), 0));
//        }
//
//        return ResultBean.ok();
//    }

    @GetMapping("/Cache")
    public void Cache(){
        final String DISTRICTNAME = "永春";

        String s = HttpClientUtil.doGet("http://10.35.80.145:8082/radar");
        JSONObject object = JSONObject.parseObject(s);
        JSONArray datas = object.getJSONArray("data2");

        List<RainfallPerHourVo> list = new ArrayList<>();
        TotalVo totalVo = new TotalVo();
        List<TotalPerHourVo> totalList = new ArrayList<>();
        BigDecimal total = new BigDecimal(0);
        for(int i=0; i<datas.size(); i++){
            JSONArray data = datas.getJSONArray(i);
            TotalPerHourVo totalPerHourVo = new TotalPerHourVo();
            RainfallPerHourVo rainfallPerHourVo = new RainfallPerHourVo();
            rainfallPerHourVo.setTime(data.getString(0).substring(11,16));
            total = total.add(data.getBigDecimal(11).multiply(new BigDecimal(5)));
            totalPerHourVo.setTime(data.getString(0).substring(11,16));
            totalPerHourVo.setTotal(total.setScale(2,BigDecimal.ROUND_HALF_UP));
            rainfallPerHourVo.setRainfall(data.getBigDecimal(11).multiply(new BigDecimal(5)).setScale(2,BigDecimal.ROUND_HALF_UP));
            list.add(rainfallPerHourVo);
            totalList.add(totalPerHourVo);
        }
        totalVo.setName("积累降雨");
        totalVo.setTotalList(totalList);
        RainfallForecastVo rainfallForecastVo = new RainfallForecastVo();
        rainfallForecastVo.setDistrictName(DISTRICTNAME);
        rainfallForecastVo.setDataList(list);
        rainfallForecastVo.setTotal(totalVo);
        rainfallForecastVo.setRadar(object.getJSONArray("radar"));
        Date date = new Date();
        JsonFileUtil.saveDataToFile(new SimpleDateFormat("yyyyMMddHH").format(date), JSON.toJSONString(rainfallForecastVo));
        RadarRecord radarRecord = new RadarRecord();
        radarRecord.setTime(LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()));
        radarService.addRadarRecord(radarRecord);
        cacheManager.put("radar", new CacheEntity(rainfallForecastVo,1000*60*60*2L, System.currentTimeMillis()));
    }
}
